package com.springboot.interceptor;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.springboot.utils.JwtUtils;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class JwtInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("进入拦截器---");
        Map<String,Object> map = new HashMap<>();
        String token = request.getHeader("token");
        try {
            DecodedJWT verify = JwtUtils.verify(token);
            request.setAttribute("userId", verify.getClaim("userId").asString());
            request.setAttribute("username", verify.getClaim("username").asString());
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            map.put("code",400 );
            map.put("msg","token无效" );
        }
//        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().print("token无效");
        response.getWriter().flush();
        response.getWriter().close();
        return false;

    }
}
